﻿using Common;
using Common.Dtos;
using IdentityModel;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.IdentityModel.Tokens;
using Newtonsoft.Json;
using Sigma.Admin.API.Services;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;
using System.Text.Json.Serialization;

namespace Sigma.Admin.API.Controllers
{
    [ApiController]
    [Route("api/[controller]/[action]")]
    public class LoginController:ControllerBase
    {
        private readonly ILoginService service;

        public LoginController(ILoginService service)
        {
            this.service = service;
        }


        [HttpPost]
        [AllowAnonymous]
        public async Task<ApiResponse> Login([FromBody] LoginUserDto param)
        {
            //var token = CreateJwtToken();
            //return await Task.FromResult(new ApiResponse("请求成功", true, token));
            return await service.Login(param);
        }


        [HttpGet]
        [Authorize]
        public Task<ApiResponse> Test()
        {
            return Task.FromResult(new ApiResponse("失败"));
        }
        /// <summary>
        /// 颁发token-测试用
        /// </summary>
        /// <returns></returns>
        [NonAction]
        private string CreateJwtToken()
        {
            var lis = new List<string>() { "1", "2" };
            var pkey = JsonConvert.SerializeObject(lis);
            var tokenDescriptor = new SecurityTokenDescriptor
            {

                Subject = new ClaimsIdentity(new List<Claim>
                {
                    new Claim(JwtClaimTypes.Id,"1"),
                    new Claim("pkey",pkey),
                }),
                Issuer = "Auth-",
                Audience = "WPF-client",
                // 必须 Utc，默认1小时
                Expires = DateTime.UtcNow.AddMinutes(30),
                SigningCredentials = new SigningCredentials(
                new SymmetricSecurityKey(Encoding.UTF8.GetBytes("Sigma.Admin JsonWebToken WebApi")),
                SecurityAlgorithms.HmacSha256Signature),
            };

            var handler = new JwtSecurityTokenHandler();
            var securityToken = handler.CreateJwtSecurityToken(tokenDescriptor);
            var token = handler.WriteToken(securityToken);
            return token;
        }
    }
}
